package com.zhou.controller.login;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: Crazer
 * @Date: 2021/2/1 13:48
 * @version: 1.0.0
 * @Description: 登录拦截器
 */

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getRequestURI().indexOf("login.do") > 0 || request.getRequestURI().indexOf("send4Login.do") > 0) {
            return true;
        } else {
            Cookie[] cookies = request.getCookies();
            /*if (cookies != null && cookies.length > 0) {
                for (Cookie cookie : cookies) {
                    System.out.println(cookie.getName() + " " + cookie.getValue());
                }
            }*/
            Cookie login_member_telephone = CookiegetCookieByName(cookies, "login_member_telephone");
            if (login_member_telephone != null) {
                return true;
            }
            response.sendRedirect("/pages/login.html");
            return false;
        }
    }

    /**
     * 获取指定Cookie值
     * @param cookies
     * @param cookieName
     * @return
     */
    public static Cookie CookiegetCookieByName(Cookie[] cookies, String cookieName) {
        if (cookies == null) {
            return null;
        } else {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(cookieName)) {
                    return cookie;
                }
            }
            return null;
        }
    }
}
